package com.gitee.cui.basic.use;

import com.gitee.cui.util.ThreadUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 线程的yield方法演示
 * @author cuiqingqiang
 * @version 1.0
 * @date 2021/11/10 15:36
 **/
@Slf4j
public class Yield {

    private static final int MAX_TURN = 100;

    private static AtomicInteger index = new AtomicInteger(0);

    private static Map<String, AtomicInteger> metric = new HashMap<>();

    private static void printMetric() {
        log.info("metric = {}", metric);
    }

    static class YieldThread extends Thread {
        private static int threadNo = 1;
        public YieldThread() {
            super("yieldThread-" + threadNo);
            threadNo++;
            metric.put(getName(), new AtomicInteger(0));
        }

        @Override
        public void run() {
            for (int i = 0; i < MAX_TURN && index.get() < MAX_TURN; i++) {
                log.info("线程优先级：{}", getPriority());
                index.incrementAndGet();
                metric.get(getName()).incrementAndGet();
                if (i % 2 == 0) {
                    Thread.yield();
                }
            }
            printMetric();
            log.info("{} 运行结束", getName());
        }
    }

    public static void main(String[] args) {
        YieldThread thread1 = new YieldThread();
        thread1.setPriority(Thread.MAX_PRIORITY);
        YieldThread thread2 = new YieldThread();
        thread2.setPriority(Thread.MIN_PRIORITY);
        log.info("启动线程");
        thread1.start();
        thread2.start();
        ThreadUtil.sleepSeconds(100);
    }
}
